<?php

/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/4/22 13:31
 * Filename：xiaochu.php
 * 小储对接模块
 */

namespace lib\supply;


use extend\UserConf;
use lib\Hook\Hook;
use Medoo\DB\SQL;

class xiaochu
{
    /**
     * @param $OrderData 订单信息
     * @param $Goods 商品信息
     * @param $TypeSupply 对接货源信息
     * 提交下单信息！
     */
    public static function Submit($OrderData, $Goods, $TypeSupply)
    {
        global $date, $conf;
        $DB = SQL::DB();

        $DataPost = [];
        $i = 1;

        $InputArray = json_decode($OrderData['input'], TRUE);
        if ($Goods['specification'] == 2 && $Goods['specification_type'] == 2) {
            $InputArray = RuleSubmitParameters(json_decode($Goods['specification_sku'], TRUE)[0], $InputArray);
        }

        foreach ($InputArray as $value) {
            $DataPost = array_merge($DataPost, [
                'value' . $i => $value,
            ]);
            $i++;
        }

        $coupon = ($conf['CouponApiDockingOthers'] == 1 ? -2 : -1);

        $DataPost = array_merge([
            'act' => 'Docking_buy',
            'url' => href(),
            'id' => $TypeSupply['username'],
            'num' => ($OrderData['num'] * $Goods['quantity']),
            'gid' => $Goods['goods_id'],
            'encrypt' => 1,
            'type' => ($TypeSupply['secret'] == '' ? 1 : ($TypeSupply['secret'] <> 1 && $TypeSupply['secret'] <> 2 ? 1 : $TypeSupply['secret'])),
            'coupon' => $coupon,
        ], $DataPost);

        $DataPost = array_merge([
            'sign' => yile::GetSign($DataPost, $TypeSupply['password'])
        ], $DataPost);

        $HookArr = [
            'Order' => $OrderData,
            $TypeSupply['url'] => [
                'num' => ($OrderData['num'] * $Goods['quantity']),
                'goods_id' => $Goods['goods_id'],
                'DataPost' => $DataPost
            ]
        ];

        Hook::execute('XiaochuSubmit', $HookArr);

        $DataCurl = Api::SuppluCurl($TypeSupply['url'] . '/api.php', $DataPost);
        if ($DataCurl == '') return false;
        $DataCurl = json_decode(xiaochu_de($DataCurl), TRUE);
        if ($DataCurl['code'] >= 0 && isset($DataCurl['code'])) {
            /**
             * 卡密转换
             */
            if (isset($DataCurl['token'])) {
                $ii = 0;
                foreach (json_decode($DataCurl['token'], TRUE) as $v) {
                    if ($v == '') continue;
                    @$DB->insert('token', [
                        'uid' => $OrderData['uid'],
                        'gid' => $Goods['gid'],
                        'code' => $InputArray[0],
                        'token' => $v,
                        'ip' => $OrderData['ip'],
                        'order' => $OrderData['order'],
                        'endtime' => $date,
                        'addtime' => $date,
                    ]);
                    $ii++;
                }
            }

            $Msg = $DataCurl['msg'];
            $code = ($DataCurl['code'] >= 0 ? $conf['SubmitStateSuccess'] : $conf['SubmitState']);
            $money = ($DataCurl['code'] >= 0 ? $DataCurl['money'] : 0);
            $order = ($DataCurl['code'] >= 0 ? $DataCurl['order'] : -1);
        } else {
            $Msg = (empty($DataCurl['msg']) ? '下单信息获取失败!,请检查对接配置！' : $DataCurl['msg']);
            $code = $conf['SubmitState'];
            $money = 0;
            $order = -1;
        }

        $HookArr = [
            'Order' => $OrderData,
            $TypeSupply['url'] => [
                'state' => $code,
                'msg' => $Msg,
                'money' => $money,
                'order' => $order,
            ]
        ];

        Hook::execute('XiaochuFinish', $HookArr);

        return [
            'code' => $code,
            'msg' => $Msg,
            'money' => $money,
            'order' => $order,
        ];
    }

    /**
     * @param $id 订单号
     * @param $TypeSupply 对接货源信息
     */
    public static function Query($id, $TypeSupply)
    {
        $DataPost = [
            'act' => 'DockingQuery',
            'url' => href(),
            'id' => $TypeSupply['username'],
            'encrypt' => 1,
            'order' => $id
        ];

        $DataPost = array_merge([
            'sign' => yile::GetSign($DataPost, $TypeSupply['password'])
        ], $DataPost);

        $DataCurl = Api::Curl($TypeSupply['url'] . '/api.php', $DataPost);
        if ($DataCurl == '') return false;
        $DataCurl = json_decode(xiaochu_de($DataCurl), TRUE);

        if ($DataCurl['state'] <> 1) dies(-1, $DataCurl['msg']);
        $Data = $DataCurl['data'];
        return [
            'ApiType' => 1,
            'ApiNum' => $Data['num'],
            'ApiTime' => $Data['addtiem'],
            'ApiInitial' => $Data['Initial'],
            'ApiPresent' => $Data['Present'],
            'ApiState' => $Data['state'],
            'ApiError' => ($Data['remark'] <> null ? $Data['remark'] : '无'),
            'ApiExplain' => (empty($Data['Explain']) ? -1 : $Data['Explain']),
        ];
    }

    /**
     * @param $User 用户信息
     * @param $Data 传递信息
     *
     */
    public static function QueryApi($User, $Data)
    {
        $Res = Order::Query($Data['order'], $User['id']);
        $Res = $Res['data'];
        dier([
            'state' => 1,
            'msg' => '订单[' . $Data['order'] . ']数据获取成功',
            'data' => [
                'state' => ((int)$Res['ApiType'] == 1 ? $Res['ApiState'] : $Res['state']),
                'addtiem' => $Res['addtiem'],
                'num' => ((int)$Res['ApiType'] == 1 ? (int)$Res['ApiNum'] : (int)$Res['num']),
                'price' => (float)$Res['price'],
                'remark' => ($Res['remark'] == null ? $Res['ApiError'] : $Res['remark']),
                'input' => $Res['input'],
                'Initial' => ((int)$Res['ApiType'] == 1 ? $Res['ApiInitial'] : 0),
                'Present' => ((int)$Res['ApiType'] == 1 ? $Res['ApiPresent'] : 0),
                'Explain' => (!empty($Res['Explain']) ? $Res['Explain'] : -1),
            ]
        ]);
    }

    public static function GoodsArray($id, $Gid)
    {
        $DB = SQL::DB();
        $TypeSupply = $DB->get('shequ', '*', [
            'id' => $id,
        ]);
        if (!$TypeSupply) dies(-1, '货源ID：' . $id . ',不存在！');
        $DataPost = [
            'act' => 'DockingGoodsLog',
            'url' => href(),
            'id' => $TypeSupply['username'],
            'encrypt' => 1,
            'gid' => $Gid,
        ];

        $DataPost = array_merge([
            'sign' => yile::GetSign($DataPost, $TypeSupply['password'])
        ], $DataPost);

        $DataCurl = Api::Curl($TypeSupply['url'] . '/api.php', $DataPost);
        $DataCurl = json_decode(xiaochu_de($DataCurl), TRUE);
        return $DataCurl;
    }

    public static function GoodsListArr($id)
    {
        $DB = SQL::DB();

        $TypeSupply = $DB->get('shequ', '*', [
            'id' => $id,
        ]);
        if (!$TypeSupply) dies(-1, '货源ID：' . $id . ',不存在！');
        $DataPost = [
            'act' => 'DockingGoodsList',
            'url' => href(),
            'id' => $TypeSupply['username'],
            'encrypt' => 1,
        ];

        $DataPost = array_merge([
            'sign' => yile::GetSign($DataPost, $TypeSupply['password'])
        ], $DataPost);
        $DataCurl = Api::Curl($TypeSupply['url'] . '/api.php', $DataPost);
        $DataCurl = json_decode(xiaochu_de($DataCurl), TRUE);
        return $DataCurl;
    }

    /**
     * @param $Data 传递数据
     * 同系统互交数据验证模块
     */
    public static function verify($Data)
    {
        global $accredit, $conf;
        if ($conf['ShutDownUserSystem'] == -1) dies(-1, $conf['ShutDownUserSystemCause']);
        if (empty($Data['sign']) || empty($Data['url']) || empty((int)$Data['id'])) dies(-1, '对接数据缺失,请填写完整哦！');
        if (strlen($Data['sign']) <> 32) dies(-1, 'sign长度不正确,正常长度应该是32位,请重置您的token对接密钥再试试！');
        $DB = SQL::DB();
        $User = $DB->get('user', '*', ['id' => $Data['id']]);
        if (!$User) dies(-1, '用户验证失败,无此用户！');
        if ($User['state'] <> 1) dies(-1, '您的账户已被禁封！');
        if ($User['ip_white_list'] == '') dies(-1, 'IP：' . userip() . ' 未设置对接白名单！');
        $ArrayIp = explode('|', $User['ip_white_list']);
        if (!in_array(userip(), $ArrayIp)) dies(-4, 'IP：' . userip() . ' 未设置对接白名单！');
        if ($Data['sign'] !== yile::GetSign($Data, $User['token'])) dies(-1, 'sign验证失败,请确认您的版本<br>和此站版本(' . $accredit['versions'] . ')一致');
        if ($Data['url'] == href()) dies(-1, '不能对接自己哦！');
        return $User;
    }

    /**
     * @param $User 用户信息
     * @param $Data 下单商品数据
     * api对接下单！
     */
    public static function Buy($User, $Data)
    {
        global $conf;
        $DB = SQL::DB();
        $GoodsHide = UserConf::GoodsHide(); //取出不显示商品ID

        if (count($GoodsHide) >= 1) {
            if (in_array($Data['gid'], $GoodsHide)) dies(-1, '商品已下架！');
        }

        $Goods = $DB->get('goods', ['quantity', 'value', 'money', 'specification', 'specification_set', 'specification_sku'], ['gid' => $Data['gid'], 'state' => 1]);
        if (!$Goods) dies(-1, '抱歉,此商品已下架或不存在,无法被对接!');
        $DataInput = explode('|', $Goods['value']);

        if ($Goods['specification'] == 2) {
            $SpRule = RlueAnalysis($Goods['specification_set'], $Goods, 3, false);
            if ($SpRule != -1) $DataInput = array_merge($SpRule['MasterRule'], $DataInput);
            if (empty($Goods['value']) && $SpRule != -1) $DataInput = $SpRule['MasterRule'];
        }

        $InputArr = [];
        $i = 1;
        foreach ($DataInput as $value) {
            if (strstr($value, '{') && strstr($value, '}')) {
                $value = explode('{', $value)[0];
            }
            if (empty($Data['value' . $i])) dies(-1, '下单信息缺失,请将[' . $value . ']填写完整');
            $InputArr[] = $Data['value' . $i];
            $i++;
        }


        if ($conf['CouponApiBeDocking'] == 2) {
            $CouponId = -1;
        } else {
            $Coupon = (empty($Data['coupon']) ? -1 : $Data['coupon']);
            if ($Coupon == -1) {
                $CouponId = -1;
            } else $CouponId = $Data['coupon'];
        }

        $Data = [
            'gid' => $Data['gid'],
            'type' => ($Data['type'] + 1),
            'num' => ($Data['num'] / $Goods['quantity']),
            'data' => $InputArr,
            'mode' => 'alipay',
            'Api' => 1,
            'CouponId' => $CouponId
        ];

        $order = Order::Creation($Data, $User);
        if ($order <> false) {
            $OrderData = $DB->get('order', '*', [
                'id' => $order,
            ]);
            $User = $DB->get('user', '*', ['id' => $User['id']]);

            $Return = [
                'code' => 1,
                'order' => $OrderData['order'],
                'money' => (($Data['type'] - 1) == 1 ? $User['money'] : $User['currency']),
                'msg' => '订单创建成功,购买后剩余' . (($Data['type'] - 1) == 1 ? $User['money'] . '余额!' : $User['currency'] . '积分!'),
            ];

            $OrderToken = $DB->select('token', ['token'], ['order' => $OrderData['order']]);
            if ($OrderToken && count($OrderToken) >= 1) {
                $ArrayToken = [];
                foreach ($OrderToken as $value) {
                    $ArrayToken[] = $value['token'];
                }
                $Return = array_merge($Return, [
                    'token' => json_encode($ArrayToken),
                    'msg' => $Return['msg'] . '，另,本次共发卡' . count($ArrayToken) . '张！',
                ]);
            }
            dier($Return);
        } else dies(-1, '订单创建失败,请联系管理员处理！');
    }

    /**
     * @return array
     * 取出商品列表
     */
    public static function GoodsList()
    {
        $DB = SQL::DB();
        $GoodsHide = UserConf::GoodsHide(); //取出不显示商品ID
        $SQL = [
            'state' => 1,
            'ORDER' => ['sort' => 'DESC'],
        ];
        if (count($GoodsHide) >= 1) {
            $SQL = array_merge($SQL, [
                'gid[!]' => $GoodsHide
            ]);
        }
        $Res = $DB->select('goods', [
            'gid', 'cid', 'name(title)', 'method'
        ], $SQL);
        $Data = [];
        foreach ($Res as $v) {
            if (!in_array(4, json_decode($v['method'], TRUE))) continue;
            unset($v['method']);
            $Data[] = $v;
        }
        return [
            'state' => 1,
            'msg' => '商品列表获取成功',
            'data' => $Data
        ];
    }

    public static function GoodsLog($User, $Gid)
    {
        $DB = SQL::DB();

        $GoodsHide = UserConf::GoodsHide();

        if (count($GoodsHide) >= 1) {
            if (in_array($Gid, $GoodsHide)) dies(-1, '商品已下架！');
        }

        $Goods = $DB->get('goods', [
            'gid', 'cid', 'name', 'method',
            'min', 'max', 'image', 'picture',
            'method', 'value', 'docs(content)',
            'alert', 'profits', 'money', 'quantity', 'custom',
            'specification_set', 'specification', 'specification_sku',
        ], [
            'gid' => $Gid,
            'LIMIT' => 1,
            'state' => 1,
        ]);

        if (!$Goods) dies(-1, '商品已下架或不存在！');
        if (!in_array(4, json_decode($Goods['method'], TRUE))) dies(-1, '此商品无法被对接！');

        $Input = explode('|', $Goods['value']);
        if ($Goods['specification'] == 2) {
            $SpRule = RlueAnalysis($Goods['specification_set'], $Goods, 1, false, $User);

            if ($SpRule != -1) $Input = array_merge($SpRule['MasterRule'], $Input);
            if (empty($Goods['value']) && $SpRule != -1) $Input = $SpRule['MasterRule'];

            $Ar1 = explode('&|||&', $Goods['specification_set']);
            $parameter =  explode('&///&', $Ar1[0]);

            $PriRule = [];
            foreach ($SpRule['Parameter'] as $k => $v) {
                $ArrRule = explode('|*|', $parameter[$k]);
                $ArrRule[0] =  $v['price'];
                $ArrRule[4] = ImageUrl($ArrRule[4]);
                $PriRule[] = implode('|*|', $ArrRule);
            }
            $PriRuleR = implode('&///&', $PriRule);
            $Goods['specification_set'] = $PriRuleR . '&|||&' . $Ar1[1];
        }
        $Goods['specification'] = intval($Goods['specification']);
        $a = 1;
        $InputArr = [];
        foreach ($Input as $v) {
            $InputArr[] = 'value' . $a;
            ++$a;
        }
        $Price = \price::price_uid($User['grade'], $Goods['profits'], $Goods['money'], $Goods['custom'], UserConf::GoodsPrice($Goods['gid']));
        unset($Goods['profits'], $Goods['money'], $Goods['method']);
        $Goods = array_merge($Goods, [
            'price' => $Price['price'],
            'points' => $Price['points'],
            'level' => $Price['level'],
            'level_arr' => $Price['level_arr'],
            'inputs' => $InputArr,
            'input' => $Input
        ]);

        return [
            'state' => 1,
            'msg' => '商品详情获取成功',
            'data' => $Goods,
        ];
    }
}
